<?php
// +----------------------------------------------------------------------
// | ThinkPHP
// +----------------------------------------------------------------------
// | Copyright (c) 2008 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$

/* 分类树 */
function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0)
{
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/* 排序 */
function sortBy($list,$field, $sortby='asc' )
{
       if(is_array($list)){
           $refer = $resultSet = array();
           foreach ($list as $i => $data)
               $refer[$i] = &$data[$field];
           switch ($sortby) {
               case 'asc':
                    asort($refer);
                    break;
               case 'desc':
                    arsort($refer);
                    break;
               case 'nat':
                    natcasesort($refer);
                    break;
           }
           foreach ( $refer as $key=> $val)
               $resultSet[] = &$list[$key];
           return $resultSet;
       }
       return false;
}

/* 数组搜索*/
function search($list,$condition)
{
   if(is_string($condition))
        parse_str($condition,$condition);
        $resultSet = array();
        foreach ($list as $key=>$data)
        {
            $find   =   false;
            foreach ($condition as $field=>$value)
            {
                if(isset($data[$field]))
                {
                    if(0 === strpos($value,'/'))
                    {
                        $find   =   preg_match($value,$data[$field]);
                    }
                    elseif($data[$field]==$value)
                    {
                        $find = true;
                    }
                }
            }
            if($find)
                $resultSet[]     =   &$list[$key];
        }
        return $resultSet;
}

/* 显示标签*/
function showTags($tags)
{
	$tags = explode(' ',$tags);
    $str = '';
    foreach($tags as $key=>$val) {
    	$tag =  trim($val);
        $str  .= ' <a href="'.__URL__.'/tag/'.urlencode($tag).'">'.$tag.'</a>  ';
    }
    return $str;
}

/* 内容处理 */
function getAbstract($content,$id)
{
    if(false !== $pos=strpos($content,'[separator]')) {
        $content  =  substr($content,0,$pos).'  <P> (<a href="'.__URL__.'/'.$id.'"><B>阅读全部内容… </B></a>) ';
    }
    return $content;
}
/* 处理内容*/
function removeAbstract($content)
{
        return str_replace('[separator]','',$content);
}

/* 处理大小 */
function getTitleSize($count)
{
    $size = (ceil($count/10)+11).'px';
    return $size;
}

/* 颜色处理 */
function rcolor() {
    $rand = rand(0,255);
    return sprintf("%02X","$rand");
}

/* 颜色处理 */
function rand_color()
{
	return '#'.rcolor().rcolor().rcolor();
}

/* 数据缓存*/
function cache($name,$value='',$expire=60)
{
	if(''===$value)
    {
		return xcache_get($name);
	}
    else
    {
		if(is_null($value))
        {
			xcache_unset($name);
		}
        else
        {
			xcache_set($name,$value,$expire);
		}
	}
}

/* 主题管理 */
function getDefaultStyle($style) {
    if(empty($style)) {
        return 'blue';
    }else{
        return $style;
    }
}

/* 推荐*/
function getRecommend($type)
{
	switch($type) {
		case 1: $icon = '<IMG SRC="'.APP_PUBLIC_PATH.'/images/brand.gif" BORDER="0" align="absmiddle" ALT="">';break;
	default:
		$icon = '';
	}
	return $icon;
}

/* 密码处理 */
function pwdHash($password,$type='md5')
{
		return hash($type,$password);
}

/* 获取Ip*/
function get_client_ip(){
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
       $ip = getenv("HTTP_CLIENT_IP");
   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
       $ip = getenv("REMOTE_ADDR");
   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
       $ip = $_SERVER['REMOTE_ADDR'];
   else
       $ip = "unknown";
   return($ip);
}

/* 生成不重复数 */
function build_count_rand ($number,$length=4,$mode=1)
{
    if($mode==1 && $length<strlen($number) )
     {
        return false;
     }
    $rand   =  array();
    for($i=0; $i<$number; $i++)
    {
        $rand[] =   rand_string($length,$mode);
    }
    $unqiue = array_unique($rand);
    if(count($unqiue)==count($rand))
    {
        return $rand;
    }
    $count   = count($rand)-count($unqiue);
    for($i=0; $i<$count*3; $i++) {
        $rand[] =   rand_string($length,$mode);
    }
    $rand = array_slice(array_unique ($rand),0,$number);
    return $rand;
}

/* 时间格式化 */
function toDate($time,$format='Y-m-d H:i:s')
{
	if( empty($time))
    {
		return '';
	}
    $format = str_replace('#',':',$format);
	return date(($format),$time);
}

/* 状态处理 */
function getStatus($status,$imageShow=true)
{
    switch($status) {
    	case 0:
            $showText   = '禁用';
            $showImg    = '<IMG SRC="'.APP_PUBLIC_PATH.'/images/locked.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="禁用">';
            break;
    	case 2:
            $showText   = '待审';
            $showImg    = '<IMG SRC="'.APP_PUBLIC_PATH.'/images/checkin.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="待审">';
            break;
    	case -1:
            $showText   = '删除';
            $showImg    = '<IMG SRC="'.APP_PUBLIC_PATH.'/images/del.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="删除">';
            break;
        case 1:
        default:
            $showText   =   '正常';
            $showImg    =   '<IMG SRC="'.APP_PUBLIC_PATH.'/images/ok.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="正常">';

    }
    return ($imageShow===true)? ($showImg) : $showText;

}
/* 状态显示 */
function showStatus($status,$id)
{
	switch($status)
    {
        case 0:$info	=	'<a href="javascript:resume('.$id.')">恢复</a>';break;
        case 2:$info	=	'<a href="javascript:pass('.$id.')">批准</a>';break;
        case 1:$info	=	'<a href="javascript:forbid('.$id.')">禁用</a>';break;
        case -1:$info	=	'<a href="javascript:recycle('.$id.')">还原</a>';break;
	}
	return $info;
}
/* 状态显示 */
function showRecommend($recommend,$id)
{
	switch($recommend) {
	case 0:$info	=	'<a href="javascript:recommend('.$id.')">推荐</a>';break;
	case 1:$info	=	'<a href="javascript:unrecommend('.$id.')">取消推荐</a>';break;
	}
	return $info;
}

/* 组名*/
function getGroupName($id)
{
    if($id==0) {
    	return '无上级组';
    }
	if($list = F('groupName')) {
		return $list[$id];
	}
	$dao	=	D("Role");
	$list	=	$dao->findAll(array('field'=>'id,name'));
	foreach ($list as $vo){
		$nameList[$vo['id']] = $vo['name'];
	}
	$name	=	$nameList[$id];
	F('groupName',$nameList);
    return $name;
}

/* 显示文件扩展名 */
function showExt($ext,$pic=true)
{
	static $_extPic = array(
		'dir'=>"folder.gif",
		'doc'=>'msoffice.gif',
		'rar'=>'rar.gif',
		'zip'=>'zip.gif',
		'txt'=>'text.gif',
		'pdf'=>'pdf.gif',
		'html'=>'html.gif',
		'png'=>'image.gif',
		'gif'=>'image.gif',
		'jpg'=>'image.gif',
		'php'=>'text.gif',
	);
	static $_extTxt = array(
		'dir'=>'文件夹',
		'jpg'=>'JPEG图象',
		);
	if($pic) {
		if(array_key_exists(strtolower($ext),$_extPic)) {
			$show = "<IMG SRC='".WEB_PUBLIC_PATH."/Images/extension/".$_extPic[strtolower($ext)]."' BORDER='0' alt='' align='absmiddle'>";
		}else{
			$show = "<IMG SRC='".WEB_PUBLIC_PATH."/Images/extension/common.gif' WIDTH='16' HEIGHT='16' BORDER='0' alt='文件' align='absmiddle'>";
		}
	}else{
		if(array_key_exists(strtolower($ext),$_extTxt)) {
			$show = $_extTxt[strtolower($ext)];
		}else{
			$show = $ext?$ext:'文件夹';
		}
	}

	return $show;
}

/* 处理文件大小 */
function byte_format($size, $dec=2)
{
	$a = array("B", "KB", "MB", "GB", "TB", "PB");
	$pos = 0;
	while ($size >= 1024)
    {
		 $size /= 1024;
		   $pos++;
	}
	return round($size,$dec)." ".$a[$pos];
}

/* 置顶 */
function getTop($type)
{
	switch($type) {
		case 1: $icon = '<IMG SRC="'.APP_PUBLIC_PATH.'/images/top.gif" BORDER="0" align="absmiddle" ALT="">';break;
	default:
		$icon = '';
	}
	return $icon;
}
?>